<?php

class Db
{
    public $sql = "";
    private $pdo = null;

    private $type = 'mysql';
    private $host = 'acadmysql.duc.auburn.edu';
    public $dbname = 'jzc0139db';
    private $user = 'jzc0139';
    private $passed = 'jzc0139';

    public function __construct($sql = "")
    {
        $this->sql = $sql;
        $this->pdo = new PDO("{$this->type}:host={$this->host};dbname={$this->dbname}", $this->user, $this->passed);
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    public function lists()
    {
        $stmt = $this->pdo->prepare($this->sql);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
$data = null;
$tables = null;
$str = "";
try {
    $db = new Db();

    $db->sql = "show tables";
    $tables = $db->lists();
    foreach ($tables as $item){
        foreach ($item as $v){
            $str .= $str == ""? $v: "," . $v;
        }
    }
} catch (\Exception $e) {
    $data = $e->getMessage();
}
if (!empty($_GET['sql'])) {
    try {
        $db = new Db();
        $_GET['sql'] = $db->sql = stripslashes($_GET['sql']);
        $s = trim($db->sql);
        $word = substr($s,0, 5);
        if (strcasecmp($word, "drop") == 0){
            throw new \Exception("NOT accept \"DROP\" operation.");
        }
        $data = $db->lists();
    } catch (\Exception $e) {
        $data = $e->getMessage();
    }
}
$sql = isset($_GET['sql'])?$_GET['sql']:"";
echo "
<!DOCTYPE html>
<html>
<head>
    <meta charset=\"utf-8\">
    <link rel=\"stylesheet\" href=\"./index.css\">
    <title>Database query tool</title>
</head>
<body>
<div style=\"margin-bottom: 30px;margin-top:100px;text-align: center\">
<b>All data sheets: </b>{$str}
</div>
<div class=\"input\">
    <form action=\"\">
        <textarea name=\"sql\">{$sql}</textarea>
        <div>&nbsp;<button type=\"submit\">Submit</button></div>
    </form>
</div>";

if (is_string($data)) {
    echo "
<div class=\"error\">
    <p>
        {$data}
    </p>
</div>";
} else if(is_array($data) && $data !== null) {
    echo '<table class="table table-bordered">';
    foreach ($data as $key => $value) {
        if ($key == 0) {
            echo '<thead><tr>';
            foreach ($value as $k => $_){
                echo "<th>{$k}</th>";
            }
            echo '</tr></thead>';
        }
        echo '<tr>';
        foreach ($value as $v){
            echo "<td>{$v}</td>";
        }
        echo '</tr>';
    }
}
echo '</body></html>';








